import { ref } from 'vue'

function useWebSocket() {
  const socket = ref<WebSocket | null>(null)
  const isConnected = ref(false)

  // console.log('options', options)

  // 连接 WebSocket
  const connect = (wsUrl, callback) => {
    socket.value = new WebSocket(wsUrl)

    socket.value.onopen = () => {
      isConnected.value = true
      ElMessage.success('WebSocket 连接成功')
      if (callback) {
        callback()
      }
    }

    // socket.value.onclose = () => {
    //   isConnected.value = false
    //   ElMessage.error('WebSocket 连接已断开')
    // }
  }

  // 发送消息
  const sendMessage = (message) => {
    if (isConnected.value) {
      socket.value?.send(JSON.stringify(message))
    } else {
      console.error('WebSocket is not connected.')
    }
  }

  // 断开连接
  const disconnect = () => {
    if (isConnected.value) {
      socket.value?.close()
      ElMessage.error('WebSocket 连接已断开')
    } else {
      console.error('WebSocket is not connected.')
    }
  }

  // 订阅消息
  const subscribe = (callback) => {
    if (isConnected.value) {
      socket.value?.addEventListener('message', callback)
    } else {
      console.error('WebSocket is not connected.')
    }
  }

  // 取消订阅
  const unsubscribe = (callback) => {
    if (isConnected.value) {
      socket.value?.removeEventListener('message', callback)
    } else {
      console.error('WebSocket is not connected.')
    }
  }

  // 生命周期钩子，在组件挂载时连接 WebSocket，在组件卸载时关闭连接
  // onMounted(() => {
  //   connect()
  // })

  // onUnmounted(() => {
  //   disconnect()
  // })

  // 返回需要在组件中使用的函数和状态
  return {
    connect,
    isConnected,
    sendMessage,
    disconnect,
    subscribe,
    unsubscribe
  }
}

export default useWebSocket
